import React, {useCallback, useEffect, useRef, useState} from "react";
import {RechargeRecordModel} from "@/common/apis/model";
import LocalData from "@/common/local_data";
import {openedInvoiceListApi} from "@/common/apis/home_datasource";
import {usePullDownRefresh, useReachBottom} from "@tarojs/taro";
import Utils from "@/utils/common";

import {Text, View} from "@tarojs/components";
import {Button, Cell, CellGroup, Empty} from "@antmjs/vantui";
import ShowUtils from "@/utils/show_utils";
import AssetImage from "@/common/AssetImage";


definePageConfig({
  navigationBarTitleText: '我的发票',
  enablePullDownRefresh: true,
  onReachBottomDistance: 50,
})

export default function InvoiceListPage() {
  const [items, setItems] = useState<RechargeRecordModel[]>()
  const isFetching = useRef(false);
  const pageIndex = useRef(LocalData.startPage);
  const hasMore = useRef(true)
  const fetchData = useCallback((isRefresh) => {
    if (isFetching.current) {
      return;
    }
    isFetching.current = true;
    if (isRefresh) {
      pageIndex.current = LocalData.startPage;
    }
    let newHasMore: boolean = true;
    openedInvoiceListApi(isRefresh, pageIndex.current).then((res2) => {
      if (res2) {
        newHasMore = res2.length >= LocalData.limit;
        if (isRefresh || pageIndex.current === LocalData.startPage) {
          setItems(res2)
        } else {
          setItems(prevItems => [...prevItems, ...res2]);
        }
      } else {
        newHasMore = false;
      }
      hasMore.current = newHasMore;
      isFetching.current = false;
    })
  }, [setItems]);

  useEffect(() => {
    setItems(undefined);
    fetchData(true)
    return () => {
    }
  }, [fetchData]);

  usePullDownRefresh(() => {
    fetchData(true)
  })
  useReachBottom(() => {
    if (!hasMore.current || isFetching.current) {
      return;
    }
    pageIndex.current++
    fetchData(false)
  })


  return (
    <View>
      <View style={{minHeight: "100vh", padding: "10px 0", boxSizing: 'border-box', backgroundColor: AssetImage.bg}}>
        {
          items && !Utils.isEmpty(items) ? <View>
            {
              items.map((item, index) => {
                return <RecordItem2 key={index} item={item}/>
              })
            }
          </View> : <Empty description='暂无数据'/>
        }
      </View>
    </View>
  )
}


function RecordItem2(props) {
  const item = props.item as RechargeRecordModel
  const renderCell = useCallback((value) => {
    return (<Text style={{color: 'black', fontSize: '16px'}}>{value}</Text>)
  }, []);

  return (
    <View style={{
      paddingTop: '10px'
    }}
    >
      <CellGroup inset>
        <Cell title='发票金额'>
          <Text style={{color: 'red', fontSize: '16px'}}>{ShowUtils.getDefaultPrice(item.amount)}</Text>
        </Cell>
        <Cell title='开票信息'>
          {
            renderCell(item.title ? `${item.title}(${item.no})` : '无')
          }
        </Cell>
        <Cell renderIcon='发票类型'
              renderTitle={<View
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  justifyContent: 'flex-end',
                }}
              ><View style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                alignContent: 'center'
              }}>
                {
                  renderCell(`${ShowUtils.getInvoiceType(item.invoiceType)}`)
                }
                {
                  item.url ? <Button type='primary' size='small' onClick={() => {
                    Utils.scanFile(item.url)
                  }}
                  >下载</Button> : null
                }
              </View></View>}
        >
        </Cell>
      </CellGroup>
    </View>
  )
}
